<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 聊天助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#10B981',
                        neutral: '#1F2937',
                        chatBg: '#F9FAFB',
                        userBubble: '#4F46E5',
                        aiBubble: '#FFFFFF',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'pulse-slow': 'pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    }
                },
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .typing-animation {
                display: inline-flex;
                align-items: center;
            }
            .typing-dot {
                width: 8px;
                height: 8px;
                background-color: #9CA3AF;
                border-radius: 50%;
                margin: 0 2px;
                animation: typing 1.4s infinite both;
            }
            .typing-dot:nth-child(1) {
                animation-delay: 0s;
            }
            .typing-dot:nth-child(2) {
                animation-delay: 0.2s;
            }
            .typing-dot:nth-child(3) {
                animation-delay: 0.4s;
            }
            @keyframes typing {
                0%, 60%, 100% {
                    transform: translateY(0);
                }
                30% {
                    transform: translateY(-6px);
                }
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 min-h-screen">
    <div class="flex flex-col min-h-screen">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-md">
            <div class="container mx-auto px-4 py-4 flex justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-robot text-primary text-2xl"></i>
                    <h1 class="text-xl font-bold text-neutral">AI 聊天助手</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="/reports.html" class="flex items-center space-x-1 text-sm text-gray-600 hover:text-primary transition-colors duration-200">
                        <i class="fa fa-file-text-o"></i>
                        <span>报告列表</span>
                    </a>
                    <button id="new-chat-btn" class="flex items-center space-x-1 text-sm text-gray-600 hover:text-primary transition-colors duration-200">
                        <i class="fa fa-plus-circle"></i>
                        <span>新对话</span>
                    </button>
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                        <i class="fa fa-user"></i>
                    </div>
                </div>
            </div>
        </header>
        
        <!-- 主要聊天区域 -->
        <main class="flex-1 container mx-auto px-4 py-6 flex flex-col max-w-3xl">
            <!-- 聊天历史 -->
            <div id="chat-container" class="flex-1 flex flex-col space-y-6 mb-6 overflow-y-auto scrollbar-hide pb-4">
                <!-- 欢迎消息 -->
                <div class="ai-message flex items-start space-x-3">
                    <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                        <i class="fa fa-robot"></i>
                    </div>
                    <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                        <p class="text-gray-800">你好！我是你的AI助手。有什么我可以帮助你的吗？</p>
                    </div>
                </div>
            </div>
            
            <!-- 输入区域 -->
            <div class="bg-white rounded-2xl shadow-lg p-4">
                <div class="relative">
                    <textarea 
                        id="message-input" 
                        class="w-full border border-gray-200 rounded-xl p-4 pr-12 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200 min-h-[80px] resize-none"
                        placeholder="输入你的问题..."
                        rows="2"
                    ></textarea>
                    <button id="clear-btn" class="absolute right-3 top-3 text-gray-400 hover:text-gray-600 transition-colors duration-200 opacity-0 pointer-events-none">
                        <i class="fa fa-times-circle"></i>
                    </button>
                </div>
                <div class="flex justify-end mt-3">
                    <button 
                        id="send-btn" 
                        class="flex items-center space-x-2 bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                        disabled
                    >
                        <span>发送</span>
                        <i class="fa fa-paper-plane"></i>
                    </button>
                </div>
            </div>
        </main>
        
        <!-- 底部信息 -->
        <footer class="bg-white py-4 border-t border-gray-100">
            <div class="container mx-auto px-4 text-center text-sm text-gray-500">
                <p>© 2024 AI 聊天助手 | 基于 Spring Boot 开发</p>
            </div>
        </footer>
    </div>
    
    <script>
        // 全局变量
        let conversationId = generateConversationId();
        let isTyping = false;
        
        // DOM 元素
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const chatContainer = document.getElementById('chat-container');
        const clearBtn = document.getElementById('clear-btn');
        const newChatBtn = document.getElementById('new-chat-btn');
        
        // 事件监听器
        messageInput.addEventListener('input', handleInputChange);
        sendBtn.addEventListener('click', sendMessage);
        messageInput.addEventListener('keydown', handleKeyDown);
        clearBtn.addEventListener('click', clearInput);
        newChatBtn.addEventListener('click', startNewChat);
        
        // 生成会话ID
        function generateConversationId() {
            return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }
        
        // 处理输入变化
        function handleInputChange() {
            const hasContent = messageInput.value.trim().length > 0;
            sendBtn.disabled = !hasContent;
            clearBtn.style.opacity = hasContent ? '1' : '0';
            clearBtn.style.pointerEvents = hasContent ? 'auto' : 'none';
            
            // 自动调整文本框高度
            messageInput.style.height = 'auto';
            messageInput.style.height = (messageInput.scrollHeight < 160 ? messageInput.scrollHeight : 160) + 'px';
        }
        
        // 处理键盘事件
        function handleKeyDown(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!sendBtn.disabled) {
                    sendMessage();
                }
            }
        }
        
        // 清除输入
        function clearInput() {
            messageInput.value = '';
            handleInputChange();
            messageInput.focus();
        }
        
        // 开始新对话
        function startNewChat() {
            // 重置会话ID
            conversationId = generateConversationId();
            
            // 清空聊天历史，保留欢迎消息
            const welcomeMessage = chatContainer.querySelector('.ai-message');
            chatContainer.innerHTML = '';
            chatContainer.appendChild(welcomeMessage);
            
            // 滚动到底部
            scrollToBottom();
            
            // 显示成功提示
            showToast('已开始新对话');
        }
        
        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message) return;
            
            // 清空输入框
            clearInput();
            
            // 添加用户消息到聊天界面
            addUserMessage(message);
            
            // 添加AI正在输入的提示
            const typingElement = addTypingIndicator();
            
            try {
                // 调用API获取响应
                await fetchStreamedResponse(message);
            } catch (error) {
                console.error('Error fetching response:', error);
                replaceTypingWithError(typingElement);
            }
        }
        
        // 添加用户消息
        function addUserMessage(message) {
            const userMessageHtml = `
                <div class="user-message flex items-start space-x-3 justify-end">
                    <div class="bg-userBubble rounded-2xl p-4 shadow-sm max-w-[85%] text-white">
                        <p>${escapeHtml(message)}</p>
                    </div>
                    <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary flex-shrink-0">
                        <i class="fa fa-user"></i>
                    </div>
                </div>
            `;
            
            chatContainer.insertAdjacentHTML('beforeend', userMessageHtml);
            scrollToBottom();
        }
        
        // 添加AI正在输入的提示
        function addTypingIndicator() {
            isTyping = true;
            const typingHtml = `
                <div class="ai-message flex items-start space-x-3 typing-indicator">
                    <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                        <i class="fa fa-robot"></i>
                    </div>
                    <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                        <div class="typing-animation">
                            <span class="typing-dot"></span>
                            <span class="typing-dot"></span>
                            <span class="typing-dot"></span>
                        </div>
                    </div>
                </div>
            `;
            
            chatContainer.insertAdjacentHTML('beforeend', typingHtml);
            scrollToBottom();
            return chatContainer.lastElementChild;
        }
        
        // 替换正在输入提示为错误消息
        function replaceTypingWithError(typingElement) {
            isTyping = false;
            typingElement.outerHTML = `
                <div class="ai-message flex items-start space-x-3">
                    <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                        <i class="fa fa-robot"></i>
                    </div>
                    <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                        <p class="text-red-600">抱歉，获取响应时出错。请稍后再试。</p>
                    </div>
                </div>
            `;
            scrollToBottom();
        }
        
        // 获取流式响应
        async function fetchStreamedResponse(message) {
            const url = `http://localhost:8080/ai/chat?prompt=${encodeURIComponent(message)}&conversationId=${encodeURIComponent(conversationId)}`;
            
            try {
                const response = await fetch(url);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                // 检查是否支持流式处理
                if (!response.body) {
                    throw new Error('Response body is not available');
                }
                
                // 打印响应头信息以调试
                console.log('Response headers:', [...response.headers.entries()]);
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let aiMessageElement = null;
                let isFirstChunk = true;
                let buffer = '';
                
                // 移除正在输入的提示
                const typingIndicator = document.querySelector('.typing-indicator');
                
                // 显示正在处理消息的提示
                console.log('开始接收流式响应...');
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) {
                        console.log('流式响应结束');
                        isTyping = false;
                        
                        // 如果缓冲区还有内容但没有显示，显示它
                        if (buffer.trim() && aiMessageElement) {
                            try {
                                const parsedContent = processBufferContent(buffer);
                                console.log('处理剩余缓冲区内容:', buffer, '解析结果:', parsedContent);
                                if (parsedContent) {
                                    aiMessageElement.textContent += parsedContent;
                                }
                            } catch (e) {
                                console.warn('处理剩余缓冲区内容时出错:', e);
                                // 直接添加原始内容作为后备
                                aiMessageElement.textContent += buffer;
                            }
                        }
                        
                        // 如果整个响应为空，显示默认消息
                        if (!aiMessageElement || aiMessageElement.textContent.trim() === '') {
                            console.log('没有接收到有效内容，显示默认错误消息');
                            const emptyResponseHtml = `
                                <div class="ai-message flex items-start space-x-3">
                                    <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                                        <i class="fa fa-robot"></i>
                                    </div>
                                    <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                                        <p>抱歉，我无法生成响应。请尝试重新表述您的问题。</p>
                                    </div>
                                </div>
                            `;
                            
                            if (typingIndicator) {
                                typingIndicator.outerHTML = emptyResponseHtml;
                            } else {
                                chatContainer.insertAdjacentHTML('beforeend', emptyResponseHtml);
                            }
                        }
                        
                        scrollToBottom();
                        break;
                    }
                    
                    // 解码新接收的数据
                    const chunk = decoder.decode(value, { stream: true });
                    console.log('收到数据块:', JSON.stringify(chunk));
                    
                    // 添加到缓冲区
                    buffer += chunk;
                    
                    // 尝试处理缓冲区中的完整消息
                    const { processed, remaining } = processBuffer(buffer);
                    buffer = remaining;
                    console.log('缓冲区处理结果 - 已处理:', processed, '剩余:', remaining);
                    
                    if (processed) {
                        // 处理每个完整的消息
                        for (const content of processed) {
                            const displayContent = processChatResponse(content);
                            console.log('处理响应内容:', JSON.stringify(content), '显示内容:', displayContent);
                            
                            if (displayContent) {
                                if (isFirstChunk) {
                                    // 获取父容器，用于后续查找
                                    const parentContainer = typingIndicator.parentElement;
                                    
                                    // 创建新的AI消息元素
                                    const newAiMessageHtml = `
                                        <div class="ai-message flex items-start space-x-3">
                                            <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                                                <i class="fa fa-robot"></i>
                                            </div>
                                            <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                                                <p>${escapeHtml(displayContent)}</p>
                                            </div>
                                        </div>
                                    `;
                                    
                                    // 替换元素
                                    typingIndicator.outerHTML = newAiMessageHtml;
                                    
                                    // 使用正确的ID选择器获取AI消息元素
                                    const newAiMessageElement = document.querySelector('#chat-container .ai-message:last-child p');
                                    aiMessageElement = newAiMessageElement || document.querySelector('.ai-message:last-child p');
                                    isFirstChunk = false;
                                } else if (aiMessageElement) {
                                    // 更新AI消息内容
                                    aiMessageElement.textContent += displayContent;
                                }
                                
                                scrollToBottom();
                            }
                        }
                    }
                }
                
            } catch (error) {
                console.error('流式处理错误:', error);
                // 确保正在输入状态被取消
                isTyping = false;
                
                // 显示错误消息
                const errorHtml = `
                    <div class="ai-message flex items-start space-x-3">
                        <div class="w-8 h-8 rounded-full bg-secondary/10 flex items-center justify-center text-secondary flex-shrink-0">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div class="bg-aiBubble rounded-2xl p-4 shadow-sm max-w-[85%] border border-gray-100">
                            <p class="text-red-600">获取响应时出错: ${error.message}</p>
                            <p class="text-gray-500 text-sm mt-1">请检查服务器是否正常运行，或稍后再试。</p>
                        </div>
                    </div>
                `;
                
                const typingIndicator = document.querySelector('.typing-indicator');
                if (typingIndicator) {
                    typingIndicator.outerHTML = errorHtml;
                } else {
                    chatContainer.insertAdjacentHTML('beforeend', errorHtml);
                }
                
                scrollToBottom();
            }
        }
        
        // 处理缓冲区数据，将其分割为完整的消息单元
        function processBuffer(buffer) {
            const results = [];
            let remaining = '';
            
            try {
                console.log('原始缓冲区内容:', JSON.stringify(buffer));
                
                // 正则表达式匹配data:开头的行
                const dataRegex = /^data:([\s\S]*?)$/gm;
                let match;
                
                // 找出所有data:开头的行
                while ((match = dataRegex.exec(buffer)) !== null) {
                    const dataContent = match[1].trim();
                    console.log('找到data事件:', JSON.stringify(dataContent));
                    
                    if (dataContent) {
                        results.push(dataContent);
                    }
                }
                
                // 如果没有找到data:开头的行，尝试直接按行分割
                if (results.length === 0) {
                    console.log('未找到data:开头的行，尝试按行分割');
                    const lines = buffer.split('\n');
                    for (const line of lines) {
                        const trimmedLine = line.trim();
                        if (trimmedLine) {
                            results.push(trimmedLine);
                        }
                    }
                }
            } catch (e) {
                console.warn('处理缓冲区时出错:', e);
                // 如果出错，将整个缓冲区作为一个结果
                results.push(buffer);
            }
            
            return { processed: results, remaining };
        }
        
        // 处理单个ChatResponse对象
        function processChatResponse(responseContent) {
            try {
                // 尝试将内容解析为JSON对象
                const parsed = JSON.parse(responseContent);
                
                // 首先尝试从result.output.text提取
                if (parsed.result && parsed.result.output && parsed.result.output.text) {
                    console.log('从result.output.text提取内容:', parsed.result.output.text);
                    return parsed.result.output.text;
                }
                
                // 然后尝试从results[0].output.text提取
                if (parsed.results && Array.isArray(parsed.results) && 
                    parsed.results[0] && parsed.results[0].output && parsed.results[0].output.text) {
                    console.log('从results[0].output.text提取内容:', parsed.results[0].output.text);
                    return parsed.results[0].output.text;
                }
                
                // 直接查找text字段
                if (parsed.text) {
                    console.log('直接从text字段提取内容:', parsed.text);
                    return parsed.text;
                }
                
                // 返回空字符串，不显示无效内容
                return '';
            } catch (e) {
                console.warn('无法解析响应内容:', responseContent, e);
                // 如果解析失败，返回空字符串
                return '';
            }
        }
        
        // 处理缓冲区中的剩余内容
        function processBufferContent(buffer) {
            try {
                // 尝试多种解析方法
                return processChatResponse(buffer);
            } catch (e) {
                // 直接返回原始内容
                return buffer;
            }
        }
        
        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // 滚动到底部
        function scrollToBottom() {
            setTimeout(() => {
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }, 100);
        }
        
        // 显示提示消息
        function showToast(message) {
            // 检查是否已存在toast元素
            let toast = document.querySelector('.toast-notification');
            
            if (toast) {
                // 更新现有toast
                toast.textContent = message;
                clearTimeout(toast.timeoutId);
            } else {
                // 创建新的toast元素
                toast = document.createElement('div');
                toast.className = 'toast-notification fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-neutral text-white px-4 py-2 rounded-lg shadow-lg z-50 opacity-0 transition-opacity duration-300';
                toast.textContent = message;
                document.body.appendChild(toast);
            }
            
            // 显示toast
            setTimeout(() => {
                toast.style.opacity = '1';
            }, 10);
            
            // 设置自动隐藏
            toast.timeoutId = setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => {
                    if (toast.parentNode) {
                        toast.parentNode.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }
        
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            messageInput.focus();
            
            // 模拟打字机效果显示欢迎消息
            const welcomeText = "你好！我是一名专业的就业指导考核评估专家，请问您想了解哪个行业的哪个职业呢？例如：互联网行业-数据分析师、制造业-机械工程师、金融行业-客户经理等。";
            const welcomeElement = document.querySelector('.ai-message p');
            welcomeElement.textContent = '';
            
            let index = 0;
            const typeWelcomeText = () => {
                if (index < welcomeText.length) {
                    welcomeElement.textContent += welcomeText.charAt(index);
                    index++;
                    setTimeout(typeWelcomeText, 30 + Math.random() * 50);
                }
            };
            
            // 延迟开始打字效果
            setTimeout(typeWelcomeText, 500);
        });
    </script>
</body>
</html>